package com.example.qu_tao.adapter;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.example.qu_tao.R;
import com.example.qu_tao.model.LiaoYiLiaoMessage;

import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;

public class LiaoYiLiaoAdapter extends RecyclerView.Adapter<LiaoYiLiaoAdapter.MessageViewHolder> {
    private List<LiaoYiLiaoMessage> messageList;

    public LiaoYiLiaoAdapter(List<LiaoYiLiaoMessage> messageList) {
        this.messageList = messageList;
    }

    @NonNull
    @Override
    public MessageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        // 根据消息类型加载不同的布局
        int layoutRes = viewType == 0 ? R.layout.item_message_sent : R.layout.item_message_received;
        View view = LayoutInflater.from(parent.getContext()).inflate(layoutRes, parent, false);
        return new MessageViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MessageViewHolder holder, int position) {
        LiaoYiLiaoMessage message = messageList.get(position);
        holder.messageText.setText(message.getContent());

        // 格式化时间显示
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm", Locale.getDefault());
        holder.timeText.setText(sdf.format(message.getTimestamp()));
    }

    @Override
    public int getItemCount() {
        return messageList.size();
    }

    @Override
    public int getItemViewType(int position) {
        // 0表示发送的消息，1表示接收的消息
        return messageList.get(position).isSentByUser() ? 0 : 1;
    }

    static class MessageViewHolder extends RecyclerView.ViewHolder {
        TextView messageText;
        TextView timeText;

        public MessageViewHolder(@NonNull View itemView) {
            super(itemView);
            messageText = itemView.findViewById(R.id.text_message_body);
            timeText = itemView.findViewById(R.id.text_message_time);
        }
    }
}